﻿namespace In66.Net.Share.Extensions
{
    public static class ApplicationBuilderExtension
    {
        /// <summary>
        /// 统一注册通用中间件
        /// </summary>
        /// <param name="app"></param>
        /// <returns></returns>
        public static IApplicationBuilder UseCore(this IApplicationBuilder app)
        {
            var serviceInfo = app.ApplicationServices.GetRequiredService<IServiceInfo>();
            var middlewareRegistarType = serviceInfo.StartAssembly.ExportedTypes.FirstOrDefault(m => m.IsAssignableTo(typeof(IMiddlewareRegistrar)) && m.IsNotAbstractClass(true));
            if (middlewareRegistarType is null)
            {
                throw new NullReferenceException(nameof(IMiddlewareRegistrar));
            }

            var middlewareRegistar = Activator.CreateInstance(middlewareRegistarType, app) as IMiddlewareRegistrar;
            middlewareRegistar?.UseCore();
            return app;
        }
    }
}
